package cn.kgc.boot.tcuser.controller;

import cn.kgc.boot.tcuser.entity.UploadFileComment;
import cn.kgc.boot.tcuser.service.UploadFileCommentService;
import cn.kgc.boot.util.CacheUtilDemo;
import cn.kgc.boot.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author XMF
 * @date 2021-07-30 15:07
 **/
@Controller
@RequestMapping(value = "/comment")
@Slf4j
public class UploadFileCommentController {


    @Autowired
    private UploadFileCommentService uploadFileCommentService;

    @Autowired
    private RedisUtil redisUtil;

    @ResponseBody
    @GetMapping(value = "getFileComment")
    public Map<String, Object> getFileComment(Integer fileId){
        Map<String, Object> map = new HashMap<>();
        List<UploadFileComment> uploadFileComments = uploadFileCommentService.queryFileCommentByFileId(fileId);
        map.put("code", uploadFileComments.isEmpty() ? 2 : 1);
        map.put("data", uploadFileComments);
        return map;
    }

    @ResponseBody
    @PostMapping(value = "insertComment")
    public boolean getFileComment(HttpServletRequest request, UploadFileComment uploadFileComment){
        String id = request.getSession().getId();
//        boolean b = checkComment(id);
//        if (!b){
//            return false;
//        }
        uploadFileComment.setCreateTime(LocalDateTime.now());
        int i = uploadFileCommentService.insertComment(uploadFileComment);
        return i == 1;
    }

    private boolean checkComment(String sessionId){
        String val = redisUtil.getValue(sessionId) == null ? null : redisUtil.getValue(sessionId).toString();
        if (null != val){
            Integer timeCount = Integer.parseInt(val);
            if (timeCount < 3){
                // 5分钟内评论次数
                timeCount = timeCount + 1;
                log.info("sessionId为{}五分钟内评论次数为{}", sessionId, timeCount);
                Long time = redisUtil.getTime(sessionId);
                redisUtil.setTimeValue(sessionId, timeCount, time, TimeUnit.SECONDS);
            }else{
                log.info("sessionId为{}五分钟内评论次数达到{}(上线)", sessionId, timeCount);
                return false;
            }
        }else{
            log.info("sessionId为{}五分钟内首次评论", sessionId);
            redisUtil.setTimeValue(sessionId, 1, 5L * 60, TimeUnit.SECONDS);
        }
        return true;
    }






}


